package bb.lanxing.devices.sync;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import com.github.mikephil.charting.utils.Utils;
import gov.nist.core.Separators;
import bb.lanxing.App;
import bb.lanxing.calc.processer.BiciGpsDataProcesser;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.bici.BiCiFileManager;
import bb.lanxing.lib.devices.bici.BiciController;
import bb.lanxing.lib.devices.bici.BiciDate;
import bb.lanxing.lib.devices.bici.model.BiciFile;
import bb.lanxing.lib.devices.bici.model.BiciPoint;
import bb.lanxing.lib.devices.bici.model.BiciWorkout;
import bb.lanxing.lib.devices.core.sync.DeviceFile;
import bb.lanxing.lib.devices.core.sync.DeviceSyncListener;
import bb.lanxing.lib.devices.core.sync.FitDeviceFile;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.WorkoutTitleUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BiciSyncManager extends AbsSyncManager implements BiciController.BiciListener {
    private BiciGpsDataProcesser mBiciGpsDataProcesser;
    private BiciController mController;
    private File mWorkingDir;
    private List<Trackpoint> trackpointList = new ArrayList();
    private Handler mMainHandler = new Handler(Looper.getMainLooper());
    private Runnable mTimeoutChecker = new Runnable() {
        @Override
        public void run() {
            DeviceFile currentItem = BiciSyncManager.this.getCurrentItem();
            if (currentItem != null) {
                BiciSyncManager.this.notifySyncStatus(currentItem.getId(), 4);
            }
        }
    };

    @Override
    public void delete(long j) {
    }

    @Override
    public String getPath(long j) {
        return null;
    }

    @Override
    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
    }

    @Override
    public void onPackage(int i, byte[] bArr) {
    }

    @Override
    public /* bridge */ /* synthetic */ void abort() {
        super.abort();
    }

    @Override
    public /* bridge */ /* synthetic */ void abortAll() {
        super.abortAll();
    }

    @Override
    public /* bridge */ /* synthetic */ void deleteAll() {
        super.deleteAll();
    }

    @Override
    public /* bridge */ /* synthetic */ DeviceFile getCurrentItem() {
        return super.getCurrentItem();
    }

    @Override
    public /* bridge */ /* synthetic */ DeviceFile getItem(long j) {
        return super.getItem(j);
    }

    @Override
    public /* bridge */ /* synthetic */ int getSyncState(long j) {
        return super.getSyncState(j);
    }

    @Override
    public /* bridge */ /* synthetic */ Object getTag() {
        return super.getTag();
    }

    @Override
    public /* bridge */ /* synthetic */ boolean isSynchronised(long j) {
        return super.isSynchronised(j);
    }

    @Override
    public /* bridge */ /* synthetic */ boolean isSynchronising() {
        return super.isSynchronising();
    }

    @Override
    public /* bridge */ /* synthetic */ boolean isSynchronisingWithMultiFiles() {
        return super.isSynchronisingWithMultiFiles();
    }

    @Override
    public /* bridge */ /* synthetic */ void readFileList() {
        super.readFileList();
    }

    @Override
    public /* bridge */ /* synthetic */ void registerSyncListener(DeviceSyncListener deviceSyncListener) {
        super.registerSyncListener(deviceSyncListener);
    }

    @Override
    public /* bridge */ /* synthetic */ boolean resync(DeviceFile deviceFile) {
        return super.resync(deviceFile);
    }

    @Override
    public /* bridge */ /* synthetic */ void setCurrentFile(DeviceFile deviceFile) {
        super.setCurrentFile(deviceFile);
    }

    @Override
    public /* bridge */ /* synthetic */ void setTag(Object obj) {
        super.setTag(obj);
    }

    @Override
    public /* bridge */ /* synthetic */ boolean sync() {
        return super.sync();
    }

    @Override
    public /* bridge */ /* synthetic */ boolean sync(long j) {
        return super.sync(j);
    }

    @Override
    public /* bridge */ /* synthetic */ boolean sync(DeviceFile deviceFile) {
        return super.sync(deviceFile);
    }

    @Override
    public /* bridge */ /* synthetic */ boolean sync(String str) {
        return super.sync(str);
    }

    @Override
    public /* bridge */ /* synthetic */ void unregisterSyncListener(DeviceSyncListener deviceSyncListener) {
        super.unregisterSyncListener(deviceSyncListener);
    }

    public BiciSyncManager() {
        BiciController biciController = XZDeviceHelper.getBiciController();
        this.mController = biciController;
        biciController.registerBiciListener(this);
        File file = new File(DeviceContext.getRootDir(1), this.mController.getDevice().getAddress().replaceAll(Separators.COLON, ""));
        this.mWorkingDir = file;
        if (!file.exists()) {
            this.mWorkingDir.mkdirs();
        }
    }

    @Override
    void doReadFileList() {
        List<DeviceFile> fileList = getFileList();
        if (fileList != null && !fileList.isEmpty()) {
            notifyReadFileList(fileList);
        } else {
            this.mController.getFileList();
        }
    }

    @Override
    boolean doSync(DeviceFile deviceFile) {
        this.mController.getFile(deviceFile.getName());
        return true;
    }

    @Override
    protected boolean exists(long j) {
        DeviceFile item = getItem(j);
        if (item == null) {
            return false;
        }
        File file = this.mWorkingDir;
        return new File(file, item.getName() + ".l").exists();
    }

    @Override
    public void release() {
        super.release();
        BiciController biciController = this.mController;
        if (biciController != null) {
            biciController.unregisterBiciListener(this);
            this.mController = null;
        }
    }

    private void parseBiciFiles(File file, File file2) {
        this.mMainHandler.removeCallbacks(this.mTimeoutChecker);
        DeviceFile currentItem = getCurrentItem();
        if (currentItem == null) {
            return;
        }
        if (file == null || file2 == null) {
            notifySyncStatus(currentItem.getId(), 4);
        } else if (!file.exists() || !file2.exists()) {
            notifySyncStatus(currentItem.getId(), 4);
        } else {
            BiciGpsDataProcesser biciGpsDataProcesser = this.mBiciGpsDataProcesser;
            if (biciGpsDataProcesser == null) {
                this.mBiciGpsDataProcesser = new BiciGpsDataProcesser();
            } else {
                biciGpsDataProcesser.reset();
            }
            try {
                notifySyncStatus(currentItem.getId(), 2);
                parseWorkoutInfo(currentItem.getId(), file);
                parseTrackpoint(currentItem.getId(), file2);
                notifySyncStatus(currentItem.getId(), 3);
            } catch (IOException e) {
                e(e);
                notifySyncStatus(currentItem.getId(), 4);
            }
        }
    }

    private void parseWorkoutInfo(long j, File file) throws IOException {
        byte[] bArr = new byte[60];
        if (new FileInputStream(file).read(bArr) != 60) {
            return;
        }
        BiciWorkout biciWorkout = new BiciWorkout(bArr);
        Workout byId = Workout.getById(j);
        if (byId != null) {
            byId.delete();
        }
        Workout workout = new Workout();
        UUID randomUUID = UUID.randomUUID();
        workout.setUserId(App.getContext().getUserId());
        workout.setId(j);
        workout.setSport(3);
        workout.setUuid(randomUUID.toString());
        workout.setAvgSpeed(biciWorkout.getAvgSpeed());
        biciWorkout.setCalorise(biciWorkout.getCalorise());
        workout.setDuration(biciWorkout.getDuration());
        workout.setElevationGain(biciWorkout.getElevationGain());
        workout.setElevationLoss(biciWorkout.getElevationLoss());
        workout.setStartTime(biciWorkout.getStartTime());
        workout.setEndTime(biciWorkout.getEndTime());
        workout.setMaxSpeed(biciWorkout.getMaxSpeed());
        workout.setPauseDuration(biciWorkout.getPauseDuration());
        workout.setStartCadence(biciWorkout.getStartCadence());
        workout.setEndCadence(biciWorkout.getEndCadence());
        int startWheel = biciWorkout.getStartWheel();
        int endWheel = biciWorkout.getEndWheel();
        workout.setStartWheel(startWheel);
        workout.setEndWheel(endWheel);
        float distance = biciWorkout.getDistance() * 1.593f;
        if (distance <= 0.0f && endWheel > 0 && startWheel >= 0 && endWheel > startWheel) {
            distance = (endWheel - startWheel) * 1.593f;
        }
        workout.setDistance(distance);
        workout.setLocSource(Workout.LOCATION_SOURCE_BICI);
        workout.setCadenceSource(Workout.CADENCE_SOURCE_BICI);
        workout.setTitle(WorkoutTitleUtil.buildWorkoutDefaultTitle(App.getContext(), workout));
        workout.save();
    }

    private void parseTrackpoint(long j, File file) throws IOException {
        int i;
        Workout byId = Workout.getById(j);
        if (byId == null) {
            return;
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bArr = new byte[34];
        int i2 = 0;
        while (fileInputStream.read(bArr) != -1) {
            int i3 = i2 + 1;
            BiciPoint biciPoint = new BiciPoint(bArr, i2);
            Trackpoint trackpoint = new Trackpoint();
            trackpoint.setLatitude(biciPoint.getLat() / 1000000.0f);
            trackpoint.setLongitude(biciPoint.getLon() / 1000000.0f);
            trackpoint.setAltitude(biciPoint.getAlt() / 100.0d);
            boolean isPointValid = CommonUtil.isPointValid(trackpoint);
            double d = Utils.DOUBLE_EPSILON;
            if (!isPointValid) {
                trackpoint.setLatitude(Utils.DOUBLE_EPSILON);
                trackpoint.setLongitude(Utils.DOUBLE_EPSILON);
            }
            short wheel = biciPoint.getWheel();
            if (wheel > 0) {
                i = 60000 / wheel;
                d = 1.593000054359436d * (1000.0d / wheel);
//                trackpoint = trackpoint;
            } else {
                i = 0;
            }
            trackpoint.setSpeed(d);
            trackpoint.setTime(biciPoint.getTimestamp());
            int crank = biciPoint.getCrank() == 0 ? 0 : 60000 / biciPoint.getCrank();
            if (crank > 256) {
                crank = 256;
            }
            if (crank < 0) {
                crank = 0;
            }
            trackpoint.setCadence(crank);
            trackpoint.setSumCadence(biciPoint.getCumulativecrank());
            trackpoint.setSumWheel(biciPoint.getCumulativewheel());
            trackpoint.setWheelRpm(i);
            trackpoint.setFlag(biciPoint.getFlag());
            trackpoint.setSource(2);
            trackpoint.setWorkoutId(j);
            this.mBiciGpsDataProcesser.process(trackpoint);
            storePoint(trackpoint);
            if (biciPoint.getFlag() == 2) {
                flushCache();
            }
            i2 = i3;
        }
        byId.setMaxCadence(this.mBiciGpsDataProcesser.getMaxCadence());
        byId.setAvgCadence(this.mBiciGpsDataProcesser.getAvgCadence(j));
        byId.setUpDistance(this.mBiciGpsDataProcesser.getUpDistance());
        byId.setFlatDistance(this.mBiciGpsDataProcesser.getFlatDistance());
        byId.setDownDistance(this.mBiciGpsDataProcesser.getDownDistance());
        byId.setUpDuration(this.mBiciGpsDataProcesser.getUpDuration());
        byId.setFlatDuration(this.mBiciGpsDataProcesser.getFlatDuration());
        byId.setDownDuration(this.mBiciGpsDataProcesser.getDownDuration());
        byId.setElevationGain(this.mBiciGpsDataProcesser.getElevationGain());
        byId.setElevationLoss(this.mBiciGpsDataProcesser.getElevationLoss());
        byId.setMaxGrade(this.mBiciGpsDataProcesser.getMaxGrade());
        byId.setMinGrade(this.mBiciGpsDataProcesser.getMinGrade());
        byId.setWorkStatus(Workout.STATUS_STOPED);//32
        byId.setSynchronise(true);
        byId.save();
    }

    private void flushCache() {
        Trackpoint.savePoints(this.trackpointList);
        this.trackpointList.clear();
    }

    private void storePoint(Trackpoint trackpoint) {
        this.trackpointList.add(trackpoint);
        if (this.trackpointList.size() >= 20) {
            Trackpoint.savePoints(this.trackpointList);
            this.trackpointList.clear();
        }
    }

    @Override
    public void onCmdStatus(int i, int i2) {
        DeviceFile currentItem;
        if (i != 11 || (currentItem = getCurrentItem()) == null) {
            return;
        }
        if (i2 == 0) {
            this.mMainHandler.postDelayed(this.mTimeoutChecker, 2000L);
        } else {
            notifySyncStatus(currentItem.getId(), 4);
        }
    }

    @Override
    public void onProgressUpdate(int i, int i2) {
        DeviceFile currentItem;
        if (i != 11 || (currentItem = getCurrentItem()) == null) {
            return;
        }
        this.mMainHandler.removeCallbacks(this.mTimeoutChecker);
        notifyProgressUpdate(currentItem.getId(), i2);
        this.mMainHandler.postDelayed(this.mTimeoutChecker, 2000L);
    }

    @Override
    public void onGetFile(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        File file = new File(str);
        String lowerCase = file.getName().toLowerCase();
        if ("filelist".equalsIgnoreCase(lowerCase)) {
            notifyReadFileList(getFileList());
        } else if (lowerCase.endsWith(".l")) {
            String substring = lowerCase.substring(0, lowerCase.lastIndexOf("."));
            String parent = file.getParent();
            parseBiciFiles(new File(parent, substring + ".h"), file);
        }
    }

    private List<DeviceFile> getFileList() {
        List<BiciFile> biCiFiles = BiCiFileManager.getInstance().getBiCiFiles();
        List<DeviceFile> arrayList = new ArrayList<>();
        if (biCiFiles != null) {
            for (BiciFile biciFile : biCiFiles) {
                FitDeviceFile fitDeviceFile = new FitDeviceFile();
                fitDeviceFile.name = String.valueOf(biciFile.getFilename());
                fitDeviceFile.size = biciFile.getSize();
                fitDeviceFile.id = biciFile.getFilename();
                fitDeviceFile.startTime = BiciDate.biciDateToTimestamp(biciFile.getFilename());
                arrayList.add(fitDeviceFile);
            }
            notifyReadFileList(arrayList);
        }
        return arrayList;
    }
}
